import ReactECharts from 'echarts-for-react';
import React from 'react';

export interface StatePeriod {
  name?: string;
  startTime?: number;
  endTime?: number;
  color?: string;
}

interface WorkingConditionChartProps {
  workStateData?: StatePeriod[];
}

function fixFloatingPoint(num: number): number {
  return parseFloat(num.toFixed(2));
}

const processData = (data: StatePeriod[]) => {
  return data
    .map((item) => {
      if (item.endTime === undefined || item.startTime === undefined) {
        console.error('endTime or startTime is undefined');
        return null;
      }
      const correctedDifference = fixFloatingPoint(item.endTime - item.startTime);

      return {
        name: item.name,
        type: 'custom',
        renderItem: (params: any, api: any) => {
          const start = api.value(0);
          const length = api.value(1);
          const x = api.coord([start, 0])[0];
          const x2 = api.coord([start + length, 0])[0];
          const height = api.size([0, 1])[1] * 0.6;
          const y = api.coord([0, 0])[1] - height / 2;

          return {
            type: 'rect',
            shape: {
              x: x,
              y: y,
              width: x2 - x,
              height: height,
            },
            style: api.style(),
          };
        },
        encode: {
          x: [0, 1],
          y: 2,
        },
        data: [[item.startTime, correctedDifference, '状态']],
        itemStyle: {
          color: item.color,
        },
      };
    })
    .filter((item) => item !== null);
};

const WorkingConditionChart: React.FC<WorkingConditionChartProps> = ({ workStateData }) => {
  if (!workStateData) {
    console.error('workStateData is undefined');
    return null;
  }

  const seriesData = processData(workStateData);

  const grid = {
    left: '0%',
    right: '5%',
    bottom: '0%',
    top: '20%',
    containLabel: true,
  };

  const xAxis = {
    type: 'value',
    min: 0,
    max: 24,
    boundaryGap: [0, 0.1],
    interval: 2,
    axisTick: { show: false },
    axisLabel: { show: true },
    splitLine: { show: false },
  };

  const yAxis = {
    type: 'category',
    data: ['状态'],
    show: false,
  };

  const option = {
    tooltip: {
      show: false,
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function (params: any) {
        let tooltipContent = '';
        params.forEach((param: any) => {
          tooltipContent += `${param.marker} ${param.seriesName}: ${param.value[1]} 小时<br/>`;
        });
        return tooltipContent;
      },
    },
    grid: grid,
    xAxis: xAxis,
    yAxis: yAxis,
    series: seriesData,
  };

  return <ReactECharts option={option} style={{ height: '90px', width: '100%' }} />;
};

export default WorkingConditionChart;
